package com.cmcc.aregister.cs.lazyimage;

import java.io.File;
import java.lang.ref.SoftReference;

import android.graphics.Bitmap;
import android.os.Handler;

import com.cmcc.aregister.cs.util.MyLogger;
import com.cmcc.aregister.cs.util.Utils;

public class HTTPThread extends Thread {
	public static final int STATUS_PENDING = 0;
	public static final int STATUS_RUNNING = 1;
	public static final int STATUS_FINISHED = 2;

	private boolean mError = false;
	private Exception mException = null;
	private String mUrl;
	private String mLocal;
	private int mType;
	private int mStatus = STATUS_PENDING;
	private SoftReference<Handler> mHandler;

	private final MyLogger logger = MyLogger.getLogger();

	public HTTPThread(String url, String local, int type, Handler handler) {
		mUrl = url;
		mLocal = local;
		mType = type;
		mHandler = new SoftReference<Handler>(handler);
	}

	@Override
	public void start() {
		if (getStatus() == STATUS_PENDING) {
			synchronized (this) {
				mStatus = STATUS_RUNNING;
			}
			super.start();
		}
	}

	public void run() {
		Bitmap bit = null;
		try {
			File file = new File(mLocal);
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
			logger.d(mUrl);
			bit = Utils.writeNetToFileImage(mUrl, file);
		} catch (Exception e) {
			logger.e(e);
			e.printStackTrace();
		} finally {
			synchronized (this) {
				mStatus = STATUS_FINISHED;
			}
			HTTPQueue.getInstance().runFirst();
			Handler handler = getHandler();
			if (handler != null) {
				handler.sendMessage(handler.obtainMessage(0, mUrl.hashCode(),
						0, bit));
			}
		}
	}

	public int getStatus() {
		synchronized (this) {
			return mStatus;
		}
	}

	public boolean hasError() {
		return mError;
	}

	public Exception getException() {
		return mException;
	}

	public void setHandler(Handler handler) {
		mHandler = new SoftReference<Handler>(handler);
	}

	public Handler getHandler() {
		if (mHandler != null) {
			return mHandler.get();
		}
		return null;
	}

	@Override
	public long getId() {
		return mUrl.hashCode();
	}
}
